const Koa = require('koa')
const app = new Koa()
const querystring = require('querystring')

app.use(async (ctx, next) => {
    if (ctx.url == '/user' && ctx.method == 'GET') {
        const buf1 = Buffer.from([1, 2, 3])
        console.log(buf1);
        
        // buf1.fill(9999)
        // console.log(buf1.toString()); // <Buffer 61 62 63> --> string(abc)
        
        ctx.set('Content-Type','text/html;charset=utf8')
        ctx.body = (
            `
                <form method="POST">
                    <input type="text" name="username" />
                    <input type="submit" />
                </form>
            `
        )
    }else { await next()}
})

app.use(async (ctx, next) => { 
    if (ctx.url == '/user' && ctx.method == 'POST') { 
        
        ctx.body = await parse(ctx.req)
        /**
         * then 是回调执行，await 会等待结果
         */
        // parse(ctx.req).then((rs) => { 
        //     console.log(rs,'rs');
        //     ctx.body = rs 
        // })
        
    }else { await next()}
})
function parse(req) { 
    let buffers = []
    return new Promise((resolve, reject) => {
        req.on('data', data => { buffers.push(data) })
        req.on('end', () => {
            console.log('end');
            let result = Buffer.concat(buffers).toString()
            console.log(querystring.parse(result),9999);
            
            resolve(querystring.parse(result))
        })
    })
}
app.listen(8080)